package com.example.museum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.museum.entity.*;
import com.example.museum.mapper.OrderItemMapper;
import com.example.museum.mapper.OrderMapper;
import com.example.museum.mapper.ShoppingCartMapper;
import com.example.museum.mapper.UserMapper;
import com.example.museum.service.OrderService;
import com.example.museum.vo.OrdersVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private UserMapper  userMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(String orderNumber, String paymentMethod) {
        // 1. 查询订单
        Orders order = orderMapper.selectBynumber(orderNumber);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 检查订单状态
        if ("paid".equals(order.getStatus()) || "shipping".equals(order.getStatus()) ||
            "completed".equals(order.getStatus())) {
            throw new RuntimeException("订单已支付，请勿重复支付");
        }

        // 3. 更新订单状态为已支付，并记录支付方式
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getNumber, orderNumber);
        updateWrapper.set(Orders::getStatus, "paid");
        updateWrapper.set(Orders::getPaymentMethod, paymentMethod);
        updateWrapper.set(Orders::getPaymentTime, LocalDateTime.now());

        return orderMapper.update(null, updateWrapper) > 0;
    }

    @Override
    public BigDecimal gettotalSales() {

        BigDecimal totalSales = orderMapper.gettotalSales();
        return totalSales;
    }

    @Override
    public Integer gettotalOrders() {

        Integer  totalOrders = orderMapper.gettotalOrders();
        return totalOrders;
    }

    @Override
    public Page<OrdersVo> listOrdersPage(Page<Orders> page, OrderQueryParam param) {
        // 构建查询条件
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        // 订单号查询
        if (StringUtils.isNotBlank(param.getNumber())) {
            queryWrapper.like(Orders::getNumber, param.getNumber());
        }

        // 用户名查询
        if (StringUtils.isNotBlank(param.getUserName())) {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.like(User::getName, param.getUserName());
            User user = userMapper.selectOne(userLambdaQueryWrapper);
            if (user != null) {
                queryWrapper.eq(Orders::getUserId, user.getId());
            }
        }

        // 订单状态查询
        if (StringUtils.isNotBlank(param.getStatus())) {
            queryWrapper.eq(Orders::getStatus, param.getStatus());
        }

        // 时间范围查询
        if (param.getStartTime() != null) {
            queryWrapper.ge(Orders::getCreateTime, param.getStartTime().atStartOfDay());
        }
        if (param.getEndTime() != null) {
            queryWrapper.le(Orders::getCreateTime, param.getEndTime().atTime(23, 59, 59));
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(Orders::getCreateTime);

        // 执行分页查询
        Page<Orders> ordersPage = orderMapper.selectPage(page, queryWrapper);

        // 转换为OrdersVo
        Page<OrdersVo> voPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, voPage, "records");

        // 转换records
        List<OrdersVo> voList = ordersPage.getRecords().stream().map(order -> {
            OrdersVo vo = new OrdersVo();
            // 复制Orders的属性
            BeanUtils.copyProperties(order, vo);

            // 查询用户信息
            User user = userMapper.selectById(order.getUserId());
            if (user != null) {
                vo.setUserName(user.getName());
            }

            // 查询订单项
            List<OrderItem> items = orderItemMapper.selectByOrderId(order.getNumber());
            vo.setItems(items);

            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);
        return voPage;

    }

    @Override
    public OrdersVo getOrderById(String number) {
        // 查询订单基本信息
        Orders orders = orderMapper.selectBynumber(number);
        if (orders == null) {
            return null;
        }

        // 转换为OrdersVo
        OrdersVo ordersVo = new OrdersVo();
        BeanUtils.copyProperties(orders, ordersVo);

        // 查询用户信息并设置用户名
        if (orders.getUserId() != null) {
            User user = userMapper.selectById(orders.getUserId());
            if (user != null) {
                // 设置用户名 - 确保使用正确的字段名
                ordersVo.setUserName(user.getUsername());
            }
        }

        // 查询订单项信息
        List<OrderItem> items = orderItemMapper.selectByOrderId(number);
        ordersVo.setItems(items);

        return ordersVo;
    }

    @Override
    public boolean updateOrderStatus(String number, String status) {

        Orders orders = new Orders();
        orders.setNumber(number);
        orders.setStatus(status);

        // 根据状态设置相应的时间字段
        LocalDateTime now = LocalDateTime.now();
        if ("paid".equals(status)) {
            orders.setPaymentTime(now);
        } else if ("shipping".equals(status)) {
            orders.setShippingTime(now);
        } else if ("completed".equals(status)) {
            orders.setCompletionTime(now);
        }

        // 确保updateById使用number作为条件而不是id
        // 使用QueryWrapper来确保按number更新
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getNumber, number);
        updateWrapper.set(Orders::getStatus, status);

        if ("paid".equals(status)) {
            updateWrapper.set(Orders::getPaymentTime, now);
        } else if ("shipping".equals(status)) {
            updateWrapper.set(Orders::getShippingTime, now);
        } else if ("completed".equals(status)) {
            updateWrapper.set(Orders::getCompletionTime, now);
        }

        return orderMapper.update(null, updateWrapper) > 0;
    }

    @Override
    @Transactional
    public OrdersVo createOrder(Orders order) {
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, order.getUserId());

        // 1. 查询购物车条目
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(shoppingCartLambdaQueryWrapper);

        if (shoppingCarts.isEmpty()) {
            throw new RuntimeException("购物车为空");
        }

        // 2. 创建订单
        Orders orders = Orders.builder()
                .userId(order.getUserId())
                .status("pending")
                .paymentMethod(order.getPaymentMethod())
                .number("ORD" + System.currentTimeMillis() + (int) (Math.random() * 900 + 100))
                .totalAmount(shoppingCarts.stream()
                        .map(item -> item.getPrice().multiply(new BigDecimal(item.getQuantity())))
                        .reduce(BigDecimal.ZERO, BigDecimal::add))
                .createTime(LocalDateTime.now())
                // 添加地址、电话和备注信息
                .address(order.getAddress())
                .phone(order.getPhone())
                .remark(order.getRemark())
                .createTime(LocalDateTime.now())
                .build();
        save(orders);

        List<String> productImages = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            productImages.add(cart.getProductImage());
        }

        // 3. 构建订单项并保存
        List<OrderItem> orderItems = new ArrayList<>();

        for (ShoppingCart cartItem : shoppingCarts) {
            OrderItem item = new OrderItem();
            item.setNumber(orders.getNumber());
            item.setProductId(cartItem.getProductId());
            item.setProductName(cartItem.getProductName());
            item.setProductImage(cartItem.getProductImage());
            item.setQuantity(cartItem.getQuantity());
            item.setPrice(cartItem.getPrice());

            orderItemMapper.insert(item);
            orderItems.add(item);
        }

        // 4. 删除购物车项
        shoppingCartMapper.deleteBatchIds(shoppingCarts.stream().map(ShoppingCart::getId).collect(Collectors.toList()));

        // 5. 返回订单Vo
        OrdersVo ordersVo = new OrdersVo();
        BeanUtils.copyProperties(orders, ordersVo);
        ordersVo.setItems(orderItems);
        return ordersVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrder(String number) {
        // 删除订单项
        LambdaQueryWrapper<OrderItem> orderItemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderItemLambdaQueryWrapper.eq(OrderItem::getNumber,number);  // 修改为正确的关联字段名
        orderItemMapper.delete(orderItemLambdaQueryWrapper);

        // 删除订单
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getNumber, number);

        return orderMapper.delete(ordersLambdaQueryWrapper) > 0;
    }



    }
